﻿using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Vaccine.API.Repositories;

namespace Vaccine.API.Infrastructure.Repositories
{
    public class VaccineInfoRepository : IVaccineInfoRepository
    {
        private readonly VaccineDbContext _vaccineDbContext;

        public VaccineInfoRepository(VaccineDbContext vaccineDbContext)
        {
            _vaccineDbContext = vaccineDbContext ?? throw new ArgumentNullException(nameof(vaccineDbContext));

            _vaccineDbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        }

        public virtual async Task<VaccineInfo> AddAsync(VaccineInfo vaccineInfo)
        {
            _vaccineDbContext.Add(vaccineInfo);

            try
            {
                await _vaccineDbContext.SaveChangesAsync();
                return vaccineInfo;
            }
            catch (DbUpdateException ex)
                when ((ex.InnerException as SqlException)?.Number == 2627)
            {
                return (await GetByIdAsync(vaccineInfo.Id))!;
            }
        }

        public virtual async Task DeleteAsync(Guid vaccineId)
        {
            var vaccineInfo = await GetByIdAsync(vaccineId);

            if (vaccineInfo == null)
            {
                return;
            }

            _vaccineDbContext.VaccineInfos.Remove(vaccineInfo);
            await _vaccineDbContext.SaveChangesAsync();
        }

        public async Task<IEnumerable<VaccineInfo>> GetAll()
        {
            return await _vaccineDbContext.VaccineInfos
                .Where(v => v.Quantity > 0)
                .ToListAsync();
        }

        public Task<VaccineInfo?> GetByIdAsync(Guid vaccineId)
        {
            return _vaccineDbContext.VaccineInfos
              .Where(o => o.Id == vaccineId)
              .SingleOrDefaultAsync();
        }

        public virtual Task UpdateAsync(VaccineInfo vaccineInfo)
        {
            _vaccineDbContext.Update(vaccineInfo);
            return _vaccineDbContext.SaveChangesAsync();
        }
    }
}
